package adnotatio.server;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class DOMUtil {

    private final static Logger log = Logger.getLogger(DOMUtil.class.getName());

    /**
     * @return
     * @throws ParserConfigurationException
     */
    private static DocumentBuilder getDocumentBuilder()
        throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            factory.setFeature("http://xml.org/sax/features/namespaces", true);
        } catch (Throwable t) {
            // Just skip it...
        }
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder;
    }

    public static Document newDocument() throws ParserConfigurationException {
        DocumentBuilder builder = getDocumentBuilder();
        return builder.newDocument();
    }

    public static Document readXML(InputStream input) throws Exception {
        return readXML(new InputStreamReader(input));
    }

    public static Document readXML(Reader reader) throws Exception {
        try {
            DocumentBuilder builder = getDocumentBuilder();
            InputSource source = new InputSource(reader);
            Document doc = builder.parse(source);
            return doc;
        } catch (Error e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            throw e;
        } finally {
            reader.close();
        }
    }
}
